package util;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import pojo.Novel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NovelText {
    public static Novel getChapteridFromUrl(String url){
        Novel novel= new Novel();
        Document document = GetHtml.getDocument(url);
        String title = document.title();
        int begin=title.indexOf("《");
        int end=title.indexOf("》");
        novel.setTitile(title.substring(begin,end+1));

        Elements noveltext = document.getElementsByClass("noveltext").eq(0);
            String text = noveltext.text();

            begin = text.indexOf("查看收藏列表 ");
            text = text.substring(begin + 7);
            String[] texts = text.split(" 　　");
            StringBuffer stringBuffer=new StringBuffer();
            for (String s : texts) {
                stringBuffer.append(s+"\n");
            }
            String finaltext=stringBuffer.toString();

            novel.setContent(finaltext);
        return novel;
    }
    public static List<Novel> getNovelByUrl(String url){
        int i=0;
        List<Novel> novels=new ArrayList<Novel>();
        //http://www.jjwxc.net/onebook.php?novelid=5588113&chapterid=
        while(true){
            i+=1;
            String chapterurl=url+"&chapterid="+i;
            if(IFNormal.isNormalHtml(chapterurl)){
                Novel novel = getChapteridFromUrl(chapterurl);
                novels.add(novel);
            }
            else {
                break;
            }
        }
        return novels;
    }
    public static void getAllNovel() throws IOException {
        List<String> novellist = GetList.getList();
        for (String novelurl : novellist) {
            novelurl="http://"+novelurl;
            List<Novel> novels = getNovelByUrl(novelurl);
            System.out.println(novels.get(0).getTitile());
            String path="D:/File/Novels/"+novels.get(0).getTitile()+".txt";
            SaveFile.saveNovel(novels,path);
        }
    }
}
